<template>
  <div class="profile" v-loading="loading">

    <div class="profile-content">
      <div class="profile-sidebar">
        <div class="user-card">
          <div class="avatar">
            <img :src="user.avatar || '/api/placeholder/100/100'" :alt="user.name" />
            <el-upload
              class="avatar-uploader"
              action="/api/user/avatar"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="{ Authorization: `Bearer ${token}` }"
            >
              <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </div>
          <h3>{{ user.name }}</h3>
          <p>{{ user.email }}</p>
        </div>

        <el-menu
          :default-active="activeTab"
          class="profile-menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="info">
            <el-icon><User /></el-icon>
            <span>基本信息</span>
          </el-menu-item>
          <el-menu-item index="learning">
            <el-icon><Document /></el-icon>
            <span>学习记录</span>
          </el-menu-item>
          <el-menu-item index="achievements">
            <el-icon><Trophy /></el-icon>
            <span>成就徽章</span>
          </el-menu-item>
          <el-menu-item index="settings">
            <el-icon><Setting /></el-icon>
            <span>账号设置</span>
          </el-menu-item>
        </el-menu>
      </div>

      <div class="profile-main">
        <div v-if="activeTab === 'info'" class="info-section">
          <h2>基本信息</h2>
          <el-form :model="user" label-width="80px">
            <el-form-item label="用户名">
              <el-input v-model="user.name" />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="user.email" />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="user.phone" />
            </el-form-item>
            <el-form-item label="个人简介">
              <el-input 
                v-model="user.bio" 
                type="textarea" 
                :rows="4" 
                placeholder="介绍一下自己..."
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateProfile" :loading="saving">保存修改</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div v-if="activeTab === 'learning'" class="learning-section">
          <h2>学习记录</h2>
          <el-timeline>
            <el-timeline-item
              v-for="record in learningRecords"
              :key="record.id"
              :timestamp="record.date"
              :type="record.type"
            >
              <h4>{{ record.title }}</h4>
              <p>{{ record.description }}</p>
            </el-timeline-item>
          </el-timeline>
          
          <!-- 学习统计 -->
          <div class="learning-stats">
            <h3>学习统计</h3>
            <div class="stats-grid">
              <div class="stat-item">
                <div class="stat-value">{{ learningStats.coursesCompleted }}</div>
                <div class="stat-label">已完成课程</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ learningStats.totalHours }}</div>
                <div class="stat-label">学习时长(小时)</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ learningStats.examsPassed }}</div>
                <div class="stat-label">通过考试</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ learningStats.points }}</div>
                <div class="stat-label">学习积分</div>
              </div>
            </div>
          </div>
        </div>

        <div v-if="activeTab === 'achievements'" class="achievements-section">
          <h2>成就徽章</h2>
          <div class="achievements-grid">
            <div 
              v-for="badge in userAchievements" 
              :key="badge.id"
              class="achievement-item"
              :class="{ earned: badge.earned }"
            >
              <div class="badge-icon">
                <el-icon><Trophy /></el-icon>
              </div>
              <h4>{{ badge.name }}</h4>
              <p>{{ badge.description }}</p>
              <div v-if="badge.earned" class="earned-date">
                获得时间: {{ badge.earnedDate }}
              </div>
              <div v-else class="not-earned">
                尚未获得
              </div>
            </div>
          </div>
        </div>

        <div v-if="activeTab === 'settings'" class="settings-section">
          <h2>账号设置</h2>
          <el-form label-width="100px">
            <el-form-item label="修改密码">
              <el-button type="primary" @click="showPasswordDialog = true">
                修改密码
              </el-button>
            </el-form-item>
            <el-form-item label="通知设置">
              <el-switch v-model="settings.emailNotifications" active-text="邮件通知" />
              <br />
              <el-switch v-model="settings.pushNotifications" active-text="推送通知" />
            </el-form-item>
            <el-form-item label="隐私设置">
              <el-switch v-model="settings.publicProfile" active-text="公开个人资料" />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="修改密码" width="400px">
      <el-form :model="passwordForm" label-width="80px">
        <el-form-item label="原密码" prop="oldPassword" :rules="[{ required: true, message: '请输入原密码', trigger: 'blur' }]">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword" :rules="[{ required: true, message: '请输入新密码', trigger: 'blur' }]">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" :rules="[{ required: true, message: '请确认新密码', trigger: 'blur' }]">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="changePassword" :loading="changingPassword">确认修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Trophy, Setting, Plus } from '@element-plus/icons-vue'
import { statisticsApi } from '@/api/exam'

const activeTab = ref('info')
const showPasswordDialog = ref(false)
const loading = ref(false)
const saving = ref(false)
const changingPassword = ref(false)
const token = localStorage.getItem('token')

const user = ref({
  name: '',
  email: '',
  phone: '',
  avatar: '',
  bio: ''
})

const learningRecords = ref([
  {
    id: 1,
    date: '2024-01-20',
    title: '完成Vue3高级开发课程',
    description: '通过了所有章节测试，获得结业证书',
    type: 'primary'
  },
  {
    id: 2,
    date: '2024-01-18',
    title: '参加TypeScript实战考试',
    description: '考试得分：85分，排名前10%',
    type: 'success'
  },
  {
    id: 3,
    date: '2024-01-15',
    title: '开始学习Vue3高级开发',
    description: '加入了Vue3高级开发课程',
    type: ''
  }
])

const learningStats = ref({
  coursesCompleted: 3,
  totalHours: 42,
  examsPassed: 5,
  points: 450
})

const userAchievements = ref([
  {
    id: 1,
    name: '初学者',
    description: '完成第一门课程',
    earned: true,
    earnedDate: '2024-01-10'
  },
  {
    id: 2,
    name: '勤奋学习者',
    description: '连续学习7天',
    earned: false
  },
  {
    id: 3,
    name: '知识探索者',
    description: '完成5门课程',
    earned: false
  }
])

const settings = ref({
  emailNotifications: true,
  pushNotifications: false,
  publicProfile: true
})

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const handleMenuSelect = (index) => {
  activeTab.value = index
}

const handleAvatarSuccess = (response, file) => {
  user.value.avatar = response.data.url
  ElMessage.success('头像上传成功')
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const updateProfile = () => {
  saving.value = true
  // 模拟保存操作
  setTimeout(() => {
    saving.value = false
    ElMessage.success('个人信息更新成功')
  }, 1000)
}

const changePassword = () => {
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  
  changingPassword.value = true
  // 模拟修改密码操作
  setTimeout(() => {
    changingPassword.value = false
    showPasswordDialog.value = false
    ElMessage.success('密码修改成功')
    // 重置表单
    passwordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
  }, 1000)
}

onMounted(() => {
  // 模拟加载用户信息
  user.value = {
    name: '张三',
    email: 'zhangsan@example.com',
    phone: '13800138000',
    avatar: '',
    bio: '热爱学习的前端开发者'
  }
})
</script>

<style scoped>
.profile {
  padding: 20px;
  background: #f0f8ff;
  min-height: calc(100vh - 140px);
}

.profile-content {
  display: flex;
  gap: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.profile-sidebar {
  width: 250px;
  background: #f8fbff;
  border-right: 1px solid #ebeef5;
}

.user-card {
  text-align: center;
  padding: 30px 20px;
  border-bottom: 1px solid #ebeef5;
}

.avatar {
  position: relative;
  width: 100px;
  height: 100px;
  margin: 0 auto 15px;
}

.avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader {
  position: absolute;
  bottom: 0;
  right: 0;
}

.avatar-uploader-icon {
  width: 30px;
  height: 30px;
  background: #2c5aa0;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.user-card h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.user-card p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.profile-menu {
  border: none;
  background: transparent;
}

.profile-main {
  flex: 1;
  padding: 30px;
}

.profile-main h2 {
  color: #2c5aa0;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.learning-stats {
  margin-top: 30px;
}

.learning-stats h3 {
  color: #2c5aa0;
  margin-bottom: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: #f8fbff;
  border-radius: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #2c5aa0;
  margin-bottom: 5px;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

.achievements-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.achievement-item {
  text-align: center;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  transition: all 0.3s;
}

.achievement-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.achievement-item.earned {
  border-color: #2c5aa0;
  background: #f0f7ff;
}

.badge-icon {
  width: 60px;
  height: 60px;
  background: #e1e8f0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 15px;
  font-size: 24px;
  color: #606266;
}

.earned .badge-icon {
  background: #2c5aa0;
  color: white;
}

.achievement-item h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.achievement-item p {
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.earned-date,
.not-earned {
  font-size: 12px;
  color: #606266;
}

.earned-date {
  color: #2c5aa0;
}

@media (max-width: 768px) {
  .profile-content {
    flex-direction: column;
  }
  
  .profile-sidebar {
    width: 100%;
  }
  
  .stats-grid,
  .achievements-grid {
    grid-template-columns: 1fr;
  }
}
</style>